import Taro from '@tarojs/taro'

let navigatingToLogin = false

const getRouterStack = () => {
  try {
    const pages = (Taro as any).getCurrentPages?.() || []
    return Array.isArray(pages) ? pages : []
  } catch (error) {
    return []
  }
}

export const openLoginPage = (options?: { message?: string }) => {
  const { message } = options || {}
  const pages = getRouterStack()
  const currentRoute = pages[pages.length - 1]?.route
  if (currentRoute === 'pages/login/index') {
    navigatingToLogin = false
    return
  }
  if (navigatingToLogin) {
    return
  }
  navigatingToLogin = true

  if (message) {
    Taro.showToast({ title: message, icon: 'none' })
  }

  const navigate = () => {
    Taro.navigateTo({
      url: '/pages/login/index',
      complete: () => {
        setTimeout(() => {
          navigatingToLogin = false
        }, 300)
      }
    })
  }

  if (message) {
    setTimeout(navigate, 500)
  } else {
    navigate()
  }
}

export const clearToken = () => {
  Taro.removeStorageSync('token')
}

export const storeToken = (token: string) => {
  Taro.setStorageSync('token', token)
}
